package com.sky.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.dto.common.PageRequest;
import com.sky.dto.common.ParamsID;
import com.sky.dto.common.QueryParams;
import com.sky.entity.CompetionCategory;
import com.sky.entity.Department;
import com.sky.entity.Instructor;
import com.sky.entity.LogicFlow;
import com.sky.exception.CommonException;
import com.sky.mapper.CompetionCategoryMapper;
import com.sky.mapper.DepartmentMapper;
import com.sky.mapper.InstructorMapeer;
import com.sky.mapper.LogicFlowMapper;
import com.sky.result.PageResult;
import com.sky.service.CompetitionCategoryService;
import com.sky.service.DepartmentService;
import com.sky.vo.CompetionCategoryVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CompetionCategoryServiceImpl implements CompetitionCategoryService {
    @Autowired
    private CompetionCategoryMapper competionCategoryMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private LogicFlowMapper logicFlowMapper;
    @Autowired
    private InstructorMapeer instructorMapeer;
    /**
     * 分页获取竞赛分类数据
     * @param queryParams
     * @return
     */
    @Override
    public PageResult getAllCompetitionCategoryList(PageRequest<QueryParams> queryParams) {
        PageHelper.startPage(queryParams.getPageNum(), queryParams.getPageSize());
        List<CompetionCategory> reslut = competionCategoryMapper.getAllList(queryParams.getParams());
        PageInfo<CompetionCategory> pageInfo = new PageInfo<>(reslut);
        List<Department> departments = departmentMapper.getDepartmentPrent();
       log.info("获取所有部门列表: {}", departments);
        // 先把所有部门放到一个 Map，方便快速根据 id 找 name
        Map<String, String> idNameMap = departments.stream()
                .collect(Collectors.toMap(dept -> String.valueOf(dept.getId()), Department::getName));
        List<CompetionCategoryVO> results = pageInfo.getList().stream().map(item -> {
            CompetionCategoryVO vo = new CompetionCategoryVO();
            BeanUtils.copyProperties(item, vo);
            String deptIdStr = item.getDepartmentId();
            if (deptIdStr != null && !deptIdStr.isEmpty()) {
                List<String> deptIds = Arrays.asList(deptIdStr.split(","));
                List<String> deptNames = deptIds.stream()
                        .map(idNameMap::get) // 取出对应的 name
                        .filter(Objects::nonNull) // 过滤掉找不到的
                        .collect(Collectors.toList());
                vo.setDepartmentIds(deptIds)
                        .setDepartmentName(deptNames);
            } else {
                vo.setDepartmentIds(Collections.emptyList()); // 空集合防止前端报错
                vo.setDepartmentName(Collections.emptyList());
            }
            // 设置当前竞赛分类状态
            LocalDateTime now = LocalDateTime.now();
            if (item.getStartTime() != null && now.isBefore(item.getStartTime())) {
                vo.setStatus( "未开始");
            } else if (item.getStartTime() != null && item.getEndTime() != null && (now.isEqual(item.getStartTime()) || (now.isAfter(item.getStartTime()) && now.isBefore(item.getEndTime())))) {
                vo.setStatus("进行中");
            } else if (item.getEndTime() != null && now.isAfter(item.getEndTime())) {
                vo.setStatus( "已结束");
            } else {
                vo.setStatus("未知");
            }
            //TODO 后期增加当前参赛人员数量之类的
            return vo;
        }).collect(Collectors.toList());
        return new PageResult(pageInfo.getTotal(), results);
    }

    /**
     * 增加竞赛分类
     * @param competionCategoryVO
     */
    @Override
    @Transactional
    public void addCompetitionCategory(CompetionCategoryVO competionCategoryVO) {
        log.info("增加竞赛分类: {}", competionCategoryVO);
        CompetionCategory competionCategory = new CompetionCategory();
        BeanUtils.copyProperties(competionCategoryVO, competionCategory);
        // 将部门ID列表转换为逗号分隔的字符串
        if (competionCategoryVO.getDepartmentIds() != null && !competionCategoryVO.getDepartmentIds().isEmpty()) {
            String deptIdStr = String.join(",", competionCategoryVO.getDepartmentIds());
            competionCategory.setDepartmentId(deptIdStr);
        } else {
            competionCategory.setDepartmentId(""); // 如果没有部门ID，设置为空字符串
        }
        competionCategoryMapper.addCompetionCategory(competionCategory);
        log.info("生成的id==============================={}",competionCategory.getId());
        //  自动配套默认的流程id
        LogicFlow logicFlow = new LogicFlow();
        // 获取一级部门的审核人员
        ParamsID paramsID = new ParamsID();
        paramsID.setIds(competionCategoryVO.getDepartmentIds());
        List<Instructor> onePeople = instructorMapeer.getOnePeople(paramsID);
        LogicFlow temp = logicFlowMapper.getById("1000");
        // 1. 解析为 Map
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        try {
            Map<String, Object> parsed = objectMapper.readValue(temp.getData(), Map.class);
            List<Map<String, Object>> nodes = (List<Map<String, Object>>) parsed.get("nodes");
            for (Map<String, Object> node : nodes) {
                Map<String, Object> props = (Map<String, Object>) node.get("properties");
                if (props != null && props.containsKey("userId")) {
                    props.put("userId",onePeople.stream().map(Instructor::getId).collect(Collectors.toList()));
                }
                if (props != null && props.containsKey("auditTime")) {
                    props.put("auditTime",Arrays.asList(competionCategoryVO.getStartTime(),competionCategoryVO.getEndTime()));
                }
            }
            String updatedJson = objectMapper.writeValueAsString(parsed);
            logicFlow.setCategoryId(competionCategory.getId())
                    .setData(updatedJson);
            logicFlowMapper.add(logicFlow);
        } catch (JsonProcessingException e) {
            log.info("解析默认流程数据失败: {}", e.getMessage());
            throw new CommonException("解析默认流程数据失败");
        }
    }

    @Override
    @Transactional
    public void deleteCompetitionCategory(ParamsID paramsID) {
        log.info("批量删除竞赛分类数据: {}", paramsID);
        if (paramsID.getIds() == null || paramsID.getIds().isEmpty()) {
            throw new CommonException(MessageConstant.COMPETITION_NUMBER_EORROR);
        }
        // 关联了竞赛的id无法删除

        // 删除逻辑流
        logicFlowMapper.deleteByCategoryId(paramsID.getIds());
        // 删除竞赛分类
        competionCategoryMapper.deleteByIds(paramsID.getIds());
        log.info("竞赛分类数据删除成功，ids: {}", paramsID.getIds());
    }

    /**
     * 获取竞赛分类详情
     * @param id
     * @return
     */
    @Override
    public CompetionCategoryVO getCompetitionCategoryDetail(String id) {
        return competionCategoryMapper.getDetail(id);
    }

    @Override
    public void updateCompetitionCategory(CompetionCategoryVO competionCategoryVO) {
        log.info("更新竞赛分类: {}", competionCategoryVO);
        // 查询当前竞赛分类是否开始，开始则无法修改
        CompetionCategory existing = competionCategoryMapper.getById(competionCategoryVO.getId());
        if(!existing.getStatus().equals(1)){
            throw new CommonException("当前竞赛分类已开始，无法修改");
        }
        CompetionCategory competionCategory = new CompetionCategory();
        BeanUtils.copyProperties(competionCategoryVO, competionCategory);
        // 将部门ID列表转换为逗号分隔的字符串
        if (competionCategoryVO.getDepartmentIds() != null && !competionCategoryVO.getDepartmentIds().isEmpty()) {
            String deptIdStr = String.join(",", competionCategoryVO.getDepartmentIds());
            competionCategory.setDepartmentId(deptIdStr);
        } else {
            competionCategory.setDepartmentId(""); // 如果没有部门ID，设置为空字符串
        }
        // 更新竞赛分类
        competionCategoryMapper.update(competionCategory);
    }

    /**
     * 获取所有竞赛分类（不分页）
     * @param queryParams 通用查询参数
     * @return
     */
    @Override
    public List<CompetionCategory> getAllCompetitionCategory(QueryParams queryParams) {
        List<CompetionCategory> competionCategoryList = new ArrayList<>();
        List<CompetionCategory> allList = competionCategoryMapper.getAllList(queryParams);
        // 拿到公有的竞赛
        List<CompetionCategory> publicList = competionCategoryMapper.getAllCompetitionCategory();
        competionCategoryList.addAll(allList);
        competionCategoryList.addAll(publicList);
        // 去重
        return competionCategoryList.stream().distinct().collect(Collectors.toList());
    }
}
